﻿using System;
using System.Windows.Forms;
using HRM.HRMServiceProxy;
using System.Data;
using System.Web.UI.WebControls;

namespace HRM
{
    public partial class frmDepartmentInfo : Form
    {
        int _DeptID;
        int _MasterID;
        int _BranchID;
        bool isChange = false;
        DepartmentInfo _DPInfo;
        DialogResult dlgResult;
        DepartmentClient wcfDP;
        RoleRightInfo listRole;

        public int DeptID
        {
            get { return _DeptID; }
            set { _DeptID = value; }
        }

        private string _DeptName;
        public string DeptName
        {
            get { return _DeptName; }
            set { _DeptName = value; }
        }

        public frmDepartmentInfo(int BranchID, int DepID, int MasterID, RoleRightInfo _listRole)
        {

            InitializeComponent();
           // LoadLanguage();
            loadBranch();
            
            //
            _DeptID = DepID;
            _MasterID = MasterID;
            _BranchID = BranchID;

            //
            loadDepartment(_BranchID);
            //
            wcfDP = Service.Department();
            dlgResult = DialogResult.Cancel;
            _DPInfo = new DepartmentInfo();

            if (_DeptID > 0)
            {
                _DPInfo = wcfDP.Department_GetInfo(_DeptID);
                Info2Form();
            }
            listRole = _listRole;
            if (!listRole._create)
                btnNew.Enabled = false;
            if (!listRole.Update)
                btnSave.Enabled = false;

            if (_MasterID > 0 || _DeptID > 0)
                cboBranch.Enabled = false;
            else
                cboBranch.Enabled = true;
            
            txtDepartmentCode.Enabled = true;
            chkHRM.Checked = true;
            chkHRM.Visible = false;
        }

        void LoadLanguage()
        {
            if (this.Tag != null)
                this.Text = UpdateUI.GetString(this.Tag.ToString());
            UpdateUI.Load_ToolStrip(ref toolStrip1);
            UpdateUI.Load_Panel(ref panel2);
        }

        private void Info2Form()
        {
            txtDepartmentCode.Text = _DPInfo.Code;
            DeptName = txtDpName.Text = _DPInfo.Name;
            txtNote.Text = _DPInfo.Description;
            cboBranch.SelectedValue = _DPInfo.BranchID;
            chkHRM.Checked = _DPInfo.IsHRM;
            isChange = false;
        }

        void Form2Info()
        {
            _DPInfo.ID = _DeptID;
            _DPInfo.Code = txtDepartmentCode.Text.Trim();
            _DPInfo.Name = txtDpName.Text;
            _DPInfo.Description = txtNote.Text;
            _DPInfo.BranchID = Convert.ToInt32(cboBranch.SelectedValue);
            _DPInfo.MasterID = Convert.ToInt32(((ListItem)cboDepartment_Name.SelectedItem).Value);
            _DPInfo.IsHRM = chkHRM.Checked;
            _DPInfo.LastUser = Program.strUserName;
            _DeptName = txtDpName.Text;
        }

        bool CheckValid()//kiểm tra dữ liệu nhập
        {
            if (txtDepartmentCode.Text.Trim().Length == 0)
            {
                txtDepartmentCode.Focus();
                MessageBox.Show("Chưa nhập mã phòng ban", UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            if (txtDpName.Text.Trim().Length == 0)
            {
                txtDpName.Focus();
                MessageBox.Show("Chưa nhập tên phòng ban", UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            if (cboBranch.Text.Trim().Length == 0)
            {
                cboBranch.Focus();
                MessageBox.Show("Chưa chọn chi nhánh", UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);               
                return false;
            }
            return true;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            bool HasChangeParentDepartment = false;
            if (!CheckValid())
            {
                isChange = true;
                return;
            }
            if (((ListItem)cboDepartment_Name.SelectedItem).Value != _MasterID.ToString())
                if (MessageBox.Show("Bạn có chắc muốn thay đổi phòng ban trực thuộc?", "Phòng ban trực thuộc đã thay đổi", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) != DialogResult.OK)
                    return;
                else
                    HasChangeParentDepartment = true;
            Form2Info();
            if (_DeptID > 0)//update
            {
                if (!listRole.Update)
                {
                    MessageBox.Show(UpdateUI.GetString("khongcoquyencapnhat"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                if (wcfDP.Department_Update(_DPInfo))
                {
                    Program.taskbarNotifier.Show(UpdateUI.GetString("thongbao"), UpdateUI.GetString("capnhatthanhcong"), UIParamater.TIME_MOVE_UP, UIParamater.TIME_SHOW, UIParamater.TIME_MOVE_DOWN);
                    isChange = false;
                    dlgResult = DialogResult.OK;
                }
                else
                {
                    MessageBox.Show(UpdateUI.GetString("capnhatkhongthanhcong"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    isChange = true;
                }
            }
            else//insert
            {
                if (!listRole.Create)
                {
                    MessageBox.Show(UpdateUI.GetString("khongcoquyenthemmoi"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                _DPInfo.ID = wcfDP.Department_Insert(_DPInfo);
                _DeptID = _DPInfo.ID;
                DeptName = _DPInfo.Name;
                if (_DPInfo.ID > 0)
                {
                    Program.taskbarNotifier.Show(UpdateUI.GetString("thongbao"), UpdateUI.GetString("themmoithanhcong"), UIParamater.TIME_MOVE_UP, UIParamater.TIME_SHOW, UIParamater.TIME_MOVE_DOWN);
                    isChange = false;
                    dlgResult = DialogResult.OK;
                }
                else
                {
                    MessageBox.Show(UpdateUI.GetString("themmoikhongthanhcong"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    isChange = true;
                }
            }
        }

        private void frmDepartmentInfo_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (isChange)
            {
                if (MessageBox.Show(UpdateUI.GetString("bandathaydoidulieu") + "\n" + UpdateUI.GetString("coluutruockhithoatkhong"), UIParamater.TitleProject, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    btnSave_Click(null, null);
                    if (isChange)
                        e.Cancel = true;
                    else
                        e.Cancel = false;
                }
            }
            this.DialogResult = dlgResult;
            //((frmDepartmentList)this.Owner).ReloadDepartmentList();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            wcfDP.Close();
            this.Close();
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            if (!listRole.Create)
            {
                MessageBox.Show(UpdateUI.GetString("khongcoquyenthemmoi"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (_DPInfo.ID == 0)
            {
                MessageBox.Show("Bạn muốn lưu trước khi tạo mới");
                return;
            }
            _DeptID = 0;
            _DPInfo = new DepartmentInfo();
            txtDepartmentCode.Text = "";
            txtDpName.Text = "";
            txtNote.Text = "";
            txtDepartmentCode.Focus();
            if (_MasterID == 0)
            {
                cboBranch.SelectedIndex = 0;
                cboBranch.Enabled = true;
            }
        }


        private void loadBranch()
        {
            BranchClient wcfBranch = Service.Branch();
            cboBranch.DisplayMember = "Branch_Name";
            cboBranch.ValueMember = "Branch_ID";
            if (!Program.isAdmin && !Program.isViewAll)
            {
                cboBranch.DataSource = wcfBranch.Branch_GetOne(Program.intBranchID).Tables[0];
            }
            else
                cboBranch.DataSource = wcfBranch.Branch_GetAll().Tables[0];            
        }

        /*Load danh sách phòng ban*/
        private void loadDepartment(int _BranchID)
        {
            cboDepartment_Name.Items.Add(new ListItem(UIParamater.CompanyName, "0"));
            //
            BranchClient wcfBranch = HRM.Service.Branch();
            DataTable dt1;
            if (!Program.isAdmin && !Program.isViewAll)
                dt1 = wcfBranch.Branch_GetOne(Program.intBranchID).Tables[0];
            else
                dt1 = wcfBranch.Branch_GetAll().Tables[0];

            LoadChilldAll(dt1);
        }

        private void LoadChilldAll(DataTable dt)
        {
            DataTable dt2;
            DepartmentClient wcfDepartment = HRM.Service.Department();
            
            foreach (DataRow dr1 in dt.Rows)
            {
                string Blank_Text = "   |-- ";
                string Branch_ID = dr1["Branch_ID"].ToString();
                //Đánh dấu node Branch
                ListItem liBranch = new ListItem(Blank_Text + dr1["Branch_Name"].ToString(), "0");
                cboDepartment_Name.Items.Add(liBranch);
                if (_DeptID == 0)
                    cboDepartment_Name.SelectedItem = liBranch;

                dt2 = wcfDepartment.Department_GetWithBranch(Convert.ToInt32(Branch_ID), 0).Tables[0];
                foreach (DataRow dr2 in dt2.Rows)
                {
                    Blank_Text = "       |-- ";
                    string Department_ID = dr2["Department_ID"].ToString();
                    string Department_Name = Blank_Text + dr2["Department_Name"].ToString();
                    if (_DeptID.ToString() != Department_ID)
                        cboDepartment_Name.Items.Add(new ListItem(Department_Name, Department_ID));
                    else
                        cboDepartment_Name.SelectedItem = liBranch;
                    AddChildNode(Convert.ToInt32(Department_ID),Department_Name,1);
                }
            }
        }

        private void AddChildNode(int Department_ID,string Department_Name, int ChildLevel)
        {
            try
            {
                string Blank_Text = "";
                for (int i = 0; i < ChildLevel; i++)
                    Blank_Text += "       ";
                Blank_Text += "       |-- ";

                DepartmentClient wcfDepartment = HRM.Service.Department();
                DataTable dt3 = LocalDB.Department_GetAllByMasterID(Department_ID.ToString());
                if (dt3.Rows.Count > 0)
                    foreach (DataRow dr3 in dt3.Rows)
                    {
                        string strDepartment_ID = dr3["Department_ID"].ToString();
                        string strDepartment_Name = Blank_Text + dr3["Department_Name"].ToString();
                        if(_DeptID.ToString() != strDepartment_ID)
                            cboDepartment_Name.Items.Add(new ListItem(strDepartment_Name, strDepartment_ID));
                        else
                            cboDepartment_Name.SelectedItem = new ListItem(Department_Name, Department_ID.ToString());
                        AddChildNode(Convert.ToInt32(strDepartment_ID),strDepartment_Name, ChildLevel+1);
                    }
            }
            catch (Exception ex)
            {
                MessageBox.Show(UpdateUI.GetString("loi") + ":\n" + ex.Message + "\n" + UpdateUI.GetString("ghiloi"));
            }
        }
        /*END load danh sách phòng ban*/

        private void frmDepartmentInfo_KeyUp(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Escape:
                    this.Dispose();
                    this.Close();
                    break;
                case Keys.F2:
                    btnNew_Click(null, null);
                    break;
                case Keys.F3:
                    btnSave_Click(null, null);
                    break;
                case Keys.Enter:
                    if (!e.Alt && !e.Control)
                    {
                        this.ProcessTabKey(!e.Shift);
                        e.Handled = true;
                    }
                    break;
            }
        }

        private void DataChange(object sender, EventArgs e)
        {
            isChange = true;
        }
    }
}
